<?php


/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use cmf\controller\RestBaseController;
use api\mall\model\StoreModel;
use think\facade\Db;
use think\facade\Log;
use api\mall\model\AddressModel;
use api\mall\model\StoreAttrModel;
use api\mall\model\StoreAttrValueModel;
use api\mall\model\ShoppingcardModel;
use api\mall\model\StoreItemTagModel;
use api\mall\model\StoreLogModel;
use api\mall\model\StoreAttrMapModel;

/**
 * @OA\Tag(
 *     name="mall-store",
 *     description="商店商品"
 * )
 */
class StoreController extends RestBaseController{
    protected function initialize() {
        parent::initialize();
        if(empty($this->user)){
            $this->error('login');
        }
        online_record($this->userId);
    }
    

    /**
     * 从购物车发起的批量购买
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/buy_from_shoppingcard",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="ids", type="integer", example="商品ID列表,逗号分割"),
     *             @OA\Property(property="nums", type="integer", example="商品数量列表,逗号分割,已取消,不可用"),
     *             @OA\Property(property="create_time", type="integer", example="下单时间,为了应付xxx"),
     *             @OA\Property(property="pay_pass", type="string", example="支付密码"),
     *             @OA\Property(property="address", type="integer", example="地址ID")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function buy_from_shoppingcard(){
        $shoppingcardM = new ShoppingcardModel();
        $model = new StoreModel();
        $addrId = $this->request->post('address/d',0);
        $create_time = $this->request->post('create_time',0);
        if(empty($create_time)){
            $create_time = time();
        }
              
        //根据子选项,获取商品的数量,价格
        $value_idstr = trim(trim($this->request->post('ids','')),',');
        if(empty($value_idstr)){
            $this->error('购物车ids?'.$this->request->post('ids'),$this->request->post());
        }
        $id_arr = explode(',', $value_idstr);
        if(empty($id_arr)){
            $this->error('选择商品');
        }
        
//        $nums_idstr = trim(trim($this->request->post('nums','')),',');
//        if(empty($nums_idstr)){
//            $this->error('购物车nums?'.$this->request->post('nums'),$this->request->post());
//        }
//        $num_arr = explode(',', $nums_idstr);
//        if(empty($num_arr)){
//            $this->error('选择商品');
//        }
//        if(count($num_arr)!=count($id_arr)){
//            $this->error('商品数量对不上');
//        }
        
        $group_id = date('YmdHis').$this->userId.'G';
        $addr_str = '';
        $addressModel = new AddressModel();
        $addr = $addressModel->where('uid',$this->userId)->where('id',$addrId)->find();
        $orders = [];
        $total_money = 0;
        
        $shopingcard_list = $shoppingcardM->whereIn('id',$id_arr)->where('user_id', $this->userId)->select();
        $item_ids = [];
        foreach ($shopingcard_list as $item){
            $item_id = $item['item_id'];
            $item_ids[] = $item_id;
        }
        if(empty($item_ids)){
            $this->error('购物车物品不存在');
        }
        
        $passwd = $this->request->post('pay_pass');
        $user = $this->user;
        if(!empty($passwd)){
            $encrypt = cmf_password($passwd);
            if($encrypt!=$user['pay_pass']){
                $this->error(['code'=>501,'msg'=>'支付密码错误']);
            }
        }
        
        
        $items = $model->whereIn('id',$item_ids)->select();
        $item_map = xx_array_to_map($items, 'id');
        $attrMapModel = new StoreAttrMapModel();
        $order_data = ['group_id'=> $group_id,'create_time'=>$create_time,'orders'=>[]];
        foreach ($shopingcard_list as &$item_sp){
            $item_id = $item_sp['item_id'];
            $item = $item_map[$item_id];
            

            if($item['item_status']!=1){
                $this->error('商品已下架,无法支付');
            }      
            
            //数字藏品类型>=1
            $prefex = 'NFT';
            if($item['booth_type']>1){           
                $prefex = 'MTM';
                if(empty($addr)){
                    $this->error('无效的收货地址');
                }
                $addr_str = $addr->toString();
            }
            
            $num = $item_sp['num'];
            if($item['check_count']){
                $price_count = $attrMapModel->where('item_id',$item_id)->where('id',$item_sp['sub_id'])->find();
                $price = $price_count['price'];
                $count = $price_count['count'];
                if($count<$num){
                    $this->error($item['item_name'].'库存不足');
                }
            }else{
                $price = $item['item_price'];
                $count=$num;
            }
            $sub_id = $item_sp['sub_id'];
            $desc = $item_sp['desc'];
            $cost = $price*$num;
            $item['sub_id'] = $sub_id;
            $item['cost'] = $cost;//保存金额,日志使用
            $item_map[$item_id] = $item;
            $total_money += $cost;
            $logid = $prefex.$group_id. count($orders);
            //加入购买记录
            $buy_log = [
                'id' =>$logid,
                'user_id'=>$this->userId,
                'create_time'=> $create_time,
                'pay_time'=>'',
                'item_id'=>$item_id,
                'item_name'=>$item['item_name'],
                'item_url'=>$item['item_icon'],
                'sub_id'=>$sub_id,
                'item_num'=>$num,
                'item_price'=>$price,
                'cost'=>$cost,
                'status'=>0,
                'attr'=>$desc,
                'desc'=>'等待支付',
                'booth_type'=>$item['booth_type'],
                'address'=>$addr_str,
                'address_id'=>$addrId,
                'group_id'=>$group_id
            ];
            $orders[] = $buy_log;
            $item_sp['logid'] = $logid;
            $order_data['orders'][] = $logid;
        }
        
        //        $price = $item->item_price;
        $dbrs = Db::name('store_log')->insertAll($orders);
        if(!$dbrs){
            $this->error('订单插入失败');
        }
        $shoppingcardM->whereIn('id',$id_arr)->where('user_id', $this->userId)->delete();
        if(empty($passwd)){
            $this->error(['code'=>201,'msg'=>'订单已生成'],$order_data);
        }
        
        
        $shoppgingcard_id = $this->request->post('spid/d',0);
        if($shoppgingcard_id>0){
            $shoppingcardM->where('user_id',$this->userId)->whereIn('id',$id_arr)->delete();
        }
        if($user->score+$user->coin<$total_money){
            $this->error(['code'=>502,'msg'=>'余额不足'],$order_data);
        }

        // 启动事务
        Db::startTrans();
        try{
            $rs = false;
            do{
                //更新余额
                //如果一方面资金不足,需要2个第二个资金账户
                //先使用coin
                if($user->coin<$total_money){
                    $score = $total_money-$user->coin;
                    $coin = $user->coin;
                }else{
                    $coin = $total_money;
                    $score = 0;
                }
                $dbrs = Db::name('user')->where('id',$this->userId)->where('balance','>=',$total_money)->dec('balance',$total_money)->update([
                    'score'=>$user->score-$score,
                    'coin'=>$user->coin-$coin
                ]);
                if(!$dbrs){
                    break;
                }
                $logs = [];
                $paytime = date('Y-m-d H:i:s');
                foreach ($shopingcard_list as $sp){
                    $itemid = $sp['item_id'];
                    $item = $item_map[$itemid];
                    $num = $sp['num'];
                    if($item['check_count']){
                        $sub_id = $item['sub_id'];
                        //更新库存
                        $dbrs = Db::name('store_attr_map')->whereIn('id',$sub_id)->where('count','>=',$num)->dec('count',$num)->update();
                        if(!$dbrs){
                            break;
                        }
                        $min = Db::name('store_attr_map')->where('item_id',$item['id'])->min('count');
                        Db::name('store_item')->where('id',$itemid)->where('item_num','>=',$num)->update(['item_num'=>$min]);
                    }
                    //添加购买记录
                    $cost = $item['cost'];
                    $user->balance=$user->balance-$cost;
                    $useCoin = 0;
                    $useScore = 0;
                    if($coin>$cost){
                        $useCoin = $cost;
                        $coin-=$cost;
                    }else{
                        $useScore = $cost-$coin;
                        $useCoin = $coin;
                        $coin = 0;
                    }
                    $log = [
                        'user_id'=>$this->userId,
                        'create_time'=> time(),
                        'score'=>$useScore*-1,
                        'coin'=>$useCoin*-1,
                        'balance'=>$user->balance,
                        'action'=>'购买'.$item->item_name.' x'.$num .','.$desc,
                        'type'=>'shopping'
                    ];
                    $logs[] = $log;
                    $desc = '待发货';
                    //数字藏品,添加到藏品表
                    if($item->booth_type==1){
                        $digital = [
                            'item_id'=>$itemid,
                            'booth_idx'=>0,
                            'user_id'=> $this->userId,
                            'create_time'=> time()
                        ];
                        Db::name('digital_collect')->insert($digital);
                        $desc = '支付成功';
                    }
                    
                    $buy_log2 = ['address'=>$addr_str,'status'=>1,'pay_time'=>$paytime,'desc'=>$desc,'address_id'=>$addrId,];
                    $logid = $sp['logid'];
                    Db::name('store_log')->where('id',$logid)->update($buy_log2);
                }
                $dbrs = Db::name('user_score_log')->insertAll($logs);
                if(!$dbrs){
                    break;
                }
                
                // 提交事务
                Db::commit();   
                $rs = true;
            }while(false);
            if(!$rs){
                //错误记录
                Log::error('[ trans ] 购买失败');
                Db::rollback();
                $this->error(['code'=>503,'msg'=>'购买失败'],$order_data);
            }
            $model->where('id',$itemid)->setInc('sell_count',$num);
        } catch (\Exception $e) {
            // 回滚事务
            Log::error('[ trans ] 购买失败:'.$e->getMessage());            
            Log::error('[ trans ] 购买失败:'.$e->getTraceAsString());
            Db::rollback();
            $this->error(['code'=>504,'msg'=>'购买失败!'],$order_data);
        }
//        $buy_log = array_merge($buy_log, $buy_log2);
//        $buy_log['item_url'] = cmf_get_image_url($buy_log['item_url']);
        Db::name('user')->where('id',$this->userId)->update(['pay_time'=>time()]);
        $this->success('购买成功',$order_data);
    }
    
    /**
     * 从旧订单发起的批量购买,根据旧订单号,判断库存,直接修改订单状态即可.
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/buy_from_order",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="integer", example="订单ID"),
     *              @OA\Property(property="pay_pass", type="string", example="支付密码"),
     *             @OA\Property(property="gid", type="integer", example="组ID,优先使用")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function buy_from_order(){
        $oid = $this->request->post('id');
        $gid = $this->request->post('gid');
        $model = new StoreLogModel();
        if(empty($oid) && empty($gid)){
            $this->error('提交订单号或者组id');
        }
        if($gid){
            $orders = $model->where('user_id',$this->userId)->where('group_id',$gid)->select();
        }else{
            $orders = $model->where('user_id',$this->userId)->where('id',$oid)->select();
        }
        if(empty($orders)){
            $this->error('无效的订单');
        }
        $cost = 0;
        $orderids = [];
        $order = [];
        foreach ($orders as $order){
            $cost += $order['cost'];
            $orderids[] = $order['id'];
        }
        if($cost==0){
            $this->error('订单无效');
        }
        $passwd = $this->request->post('pay_pass');
        if(empty($passwd)){
            $this->error(['code'=>501,'msg'=>'支付密码错误']);
        }
        $user = $this->user;
        $encrypt = cmf_password($passwd);
        if($encrypt!=$user['pay_pass']){
            $this->error(['code'=>501,'msg'=>'支付密码错误']);
        }
        
        if($user->score+$user->coin<$cost){
            $this->error('余额不足');
        }
        if($user->coin<$cost){
            $score = $cost-$user->coin;
            $coin = $user->coin;
        }else{
            $coin = $cost;
            $score = 0;
        }
        $paytime = date('Y-m-d H:i:s');
        Db::startTrans();
        $success= true;
        
        do{
        $dbrs = Db::name('user')->where('id',$this->userId)->where('balance','>=',$cost)->dec('balance',$cost)->update([
            'score'=>$user->score-$score,
            'coin'=>$user->coin-$coin
        ]);
        if(!$dbrs){
            $success = false;
            break;
        }
        $err_msg = '购买失败';
        $itemModel = new StoreModel();
        foreach ($orders as $order){
            $sub_id = $order['sub_id'];
            $num = $order['item_num'];
            $itemid = $order['item_id'];
            $item = $itemModel->where('id',$itemid)->find();
            if(empty($item)){
                $success= false;
                break;
            }
            if($item['item_status']!=1){
                $success=false;
                $err_msg = '商品已下架,无法支付';
                break;
            }
            if($item->check_count){
                //更新库存
                $dbrs = Db::name('store_attr_map')->where('id',$sub_id)->where('count','>=',$num)->dec('count',$num)->update();
//                if(!$dbrs){
//                    $success=false;
//                    break;
//                }
                $min = Db::name('store_attr_map')->where('item_id',$item->id)->min('count');
                Db::name('store_item')->where('id',$itemid)->where('item_num','>=',$num)->update(['item_num'=>$min]);
            }
            //添加购买记录
            $cost = $order['cost'];
            $user->balance=$user->balance-$cost;
            $useCoin = 0;
            $useScore = 0;
            if($coin>$cost){
                $useCoin = $cost;
                $coin-=$cost;
            }else{
                $useScore = $cost-$coin;
                $useCoin = $coin;
                $coin = 0;
            }
            $log = [
                'user_id'=>$this->userId,
                'create_time'=> time(),
                'score'=>$useScore*-1,
                'coin'=>$useCoin*-1,
                'balance'=>$user->balance,
                'action'=>'购买'.$item->item_name.' x'.$num,
                'type'=>'shopping'
            ];
            
            $dbrs = Db::name('user_score_log')->insert($log);
            if(!$dbrs){
                $success=false;
                break;
            }
            //数字藏品,添加到藏品表
            $desc = '待发货';
            if($item->booth_type==1){
                $digital = [
                    'item_id'=>$itemid,
                    'booth_idx'=>0,
                    'user_id'=> $this->userId,
                    'create_time'=> time()
                ];
                Db::name('digital_collect')->insert($digital);
                $desc = '支付成功';
            }
            $itemModel->where('id',$itemid)->setInc('sell_count',$num);
            $model->where('id',$order['id'])->update([
                'status'=>1,'pay_time'=>$paytime,'desc'=>$desc
            ]);
            }
        }while(false);
        if($success){
            Db::commit();
        }else{
            Db::rollback();
            $this->error($err_msg);
        }
        Db::name('user')->where('id',$this->userId)->update(['pay_time'=>time()]);
        $order['pay_time'] = $paytime;
        $this->success('支付成功',$order);
    }
    
    /**
     * 购买商品
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/buy",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="integer", example="商品ID"),
     *             @OA\Property(property="spid", type="integer", example="如果通过购物车来的,传购物车ID,如此购买成功后会删除购物车"),
     *             @OA\Property(property="values", type="string", example="21,22"),
     *             @OA\Property(property="num", type="integer", example="商品数量"),
     *             @OA\Property(property="$create_time", type="integer", example="下单时间,为了应付xxx"),
     *             @OA\Property(property="address", type="integer", example="地址ID"),
     *             @OA\Property(property="group", type="string", example="订单组ID,标记多个订单为一组")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function buy(){
        $itemid = $this->request->post('id');
        $num = $this->request->post('num/d',1);
        $create_time = $this->request->post('create_time', time());
        if($num<1){
            $num = 1;
        }
        $addrId = $this->request->post('address/d',0);
        $model = new StoreModel();
        $item = $model->where('id',$itemid)->find();
        if(empty($item)){
            $this->error('商品不存在');
        }
        if($item['item_status']!=1){
            $this->error('商品已下架');
        }
        $desc = $item['item_name'];
        if($item->check_count){
            //根据子选项,获取商品的数量,价格
            $value_idstr = trim(trim($this->request->post('values','')),',');
            if(empty($value_idstr)){
                $this->error('选择商品类型1'.$this->request->post('values'),$this->request->post());
            }
            $value_ids = explode(',', $value_idstr);
            if(empty($value_ids)){
                $this->error('选择商品类型2');
            }
            sort($value_ids,SORT_NUMERIC);
            $value_idstr = join(',', $value_ids);
            $attrModel = new StoreAttrMapModel();
            $attr = $attrModel->where('item_id',$itemid)->where('attr_value_id',$value_idstr)->find();
            if(empty($attr)){
                $this->error('选择商品类型');
            }
            $attrValue = new StoreAttrValueModel();
            $values = $attrValue->whereIn('v.id',$value_ids)->alias('v')
                    ->order('order_id asc')->select();
            $price = $attr['price'];
            $count = $attr['count'];
            $sub_id = $attr['id'];
            if($count<$num){
                $this->error($item['item_name'].'库存不足');
            }
            foreach ($values as $v){
                $desc .= $v['attr_value'].',';
            }
        }else{
            $price = $item['item_price'];
            $num = 1;
            $sub_id = 0;
        }
        
        
        
        $group_id = $this->request->post('group','');
        
//        if($count<$num){
//            $this->error('库存不足');
//        }
        $prefex = 'NFT';
        //数字藏品类型>=1
        if($item->booth_type>1){           
            $prefex = 'MTM';
            $addressModel = new AddressModel();
            $addr = $addressModel->where('uid',$this->userId)->where('id',$addrId)->find();
            if(empty($addr)){
                $this->error('无效的收货地址');
            }
            $addr_str = $addr->toString();
        
        }else{
            $addr_str = '';
        }

        $user = $this->user;
        $passwd = $this->request->post('pay_pass');
        if($passwd){
            $encrypt = cmf_password($passwd);
            if($encrypt!=$user['pay_pass']){
                $this->error(['code'=>501,'msg'=>'支付密码错误']);
            }
        }
        
        $cost = $price*$num;
        $logid =  $prefex.date('YmdHis').$this->userId. rand(1000,9999);
        //加入购买记录
        $buy_log = [
            'id' =>$logid,
            'user_id'=>$this->userId,
            'create_time'=> $create_time,
            'pay_time'=>'',
            'item_id'=>$itemid,
            'item_name'=>$item->item_name,
            'item_url'=>$item->item_icon,
            'item_num'=>$num,
            'item_price'=>$price,
            'cost'=>$cost,
            'status'=>0,
            'attr'=>$desc,
            'desc'=>'等待支付',
            'booth_type'=>$item->booth_type,
            'address'=>$addr_str,
            'address_id'=>$addrId,
            'sub_id'=>$sub_id,
            'group_id'=>$group_id
        ];
//        $price = $item->item_price;
       $dbrs = Db::name('store_log')->insert($buy_log);
       
        if(!$dbrs){
            $this->error('订单插入失败',$buy_log);
        }
        
        
        if(empty($passwd)){
            $this->error(['code'=>201,'msg'=>'订单已生成'],$buy_log);
        }
        
        
        $shoppgingcard_id = $this->request->post('spid/d',0);
        if($shoppgingcard_id>0){
            $shoppingcardM = new ShoppingcardModel();
            $shoppingcardM->where('user_id',$this->userId)->where('id',$shoppgingcard_id)->delete();
        }
        if($user->score+$user->coin<$cost){
            Db::name('store_log')->where('id',$logid)->update(['desc'=>'余额不足']);
            $this->error('余额不足',$buy_log);
        }

        // 启动事务
        Db::startTrans();
        try{
            $rs = false;
            do{
                //更新余额
                //如果一方面资金不足,需要2个第二个资金账户
                if($user->coin<$cost){
                    $score = $cost-$user->coin;
                    $coin = $user->coin;
                }else{
                    $coin = $cost;
                    $score = 0;
                }
                $dbrs = Db::name('user')->where('id',$this->userId)
                        ->where('score','>=',$score)
                        ->where('coin','>=',$coin)
                        ->where('balance','>=',$cost)
                        ->dec('balance',$cost)->update([
                    'score'=>$user->score-$score,
                    'coin'=>$user->coin-$coin
                ]);
                if(!$dbrs){
                    Log::error('[ trans ] 余额扣除失败');
                    break;
                }
                if($item->check_count){
                    //更新库存
                    $dbrs = Db::name('store_attr_map')->where('id',$sub_id)->where('count','>=',$num)->dec('count',$num)->update();
                    if(!$dbrs){
                        Log::error('[ trans ] 库存更新失败');
                        break;
                    }
                    $min = Db::name('store_attr_map')->where('item_id',$item->id)->min('count');
                    Db::name('store_item')->where('id',$itemid)->where('item_num','>=',$num)->update(['item_num'=>$min]);
                }
                //添加购买记录
                $log = [
                    'user_id'=>$this->userId,
                    'create_time'=> time(),
                    'score'=>$score*-1,
                    'coin'=>$coin*-1,
                    'balance'=>$user->balance-$cost,
                    'action'=>'购买'.$item->item_name.' x'.$num,
                    'type'=>'shopping'
                ];
                $dbrs = Db::name('user_score_log')->insert($log);
                if(!$dbrs){
                    break;
                }
                $paytime = date('Y-m-d H:i:s');
                $buy_log2 = ['address'=>$addr_str,'status'=>1,'pay_time'=>$paytime,'desc'=>'待发货'];
                //数字藏品,添加到藏品表
                if($item->booth_type==1){
                    $digital = [
                        'item_id'=>$itemid,
                        'booth_idx'=>0,
                        'user_id'=> $this->userId,
                        'create_time'=> time()
                    ];
                    Db::name('digital_collect')->insert($digital);
                    $buy_log2['desc']='支付成功';
                }
                
                
                Db::name('store_log')->where('id',$logid)->update($buy_log2);
                // 提交事务
                Db::commit();   
                $rs = true;
            }while(false);
            if(!$rs){
                //错误记录
                Log::error('[ trans ] 购买失败');
                Db::rollback();
                $this->error('购买失败',$buy_log);
            }
            $model->where('id',$itemid)->setInc('sell_count',$num);
        } catch (\Exception $e) {
            // 回滚事务
            Log::error('[ trans ] 购买失败:'.$e->getMessage());            
            Log::error('[ trans ] 购买失败:'.$e->getTraceAsString());
            Db::rollback();
            $this->error('购买失败',$buy_log);
        }
        Db::name('user')->where('id',$this->userId)->update(['pay_time'=>time()]);
        $buy_log = array_merge($buy_log, $buy_log2);
        $buy_log['item_url'] = cmf_get_image_url($buy_log['item_url']);
        $this->success('购买成功',$buy_log);
    }
    
    /**
     * 搜索商品列表
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/item_list",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="key", type="string", example="搜索的关键词"),     
     *             @OA\Property(property="store_type", type="integer", example="货架id"),
     *             @OA\Property(property="booth_type", type="integer", example="场景ID,数字藏品1,美容院2,零售3"),
     *             @OA\Property(property="price_min", type="number", example="价格区间,默认为0"),
     *             @OA\Property(property="price_max", type="number", example="价格区间,如果区间max值大于min,则生效,否则忽略"),
     *             @OA\Property(property="page", type="integer", example="超过一页,传入页码,获取指定页的数据")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function item_list(){
        $price0 = $this->request->post('price_min',0);
        $price1 = $this->request->post('price_max',0);

        $key = $this->request->post('key','');
        $key = trim($key);
        $type = $this->request->post('store_type');//展位
        $btype = $this->request->post('booth_type',0);
//        Log::error('log_item_list');
//        Log::error('post:'.print_r($this->request->post(),true));
//        Log::error('get:'.print_r($this->request->post(),true));
       
        //根据名称,类型搜索
        $model = new StoreModel();
        if($btype>0){
            $model=$model->where('booth_type',$btype);
        }
        if($type){
            $model=$model->where('store_type',$type);
        }
        $priceRange = ['min'=>0,'max'=>0];
        $max = $model->max('item_price');
        $min = $model->min('item_price');
        if($max){
            $priceRange = ['min'=>$min,'max'=>$max];
        }
        if($price1>$price0){
            $model=$model->where('item_price','between',[$price0,$price1]);
        }
        if(!empty($key)){
            $model = $model->where('item_type|item_name|id','like','%'.$key.'%');
        }
        $data = $model->order('item_order asc')->paginate(20);
        $data1 = $data;
        //根据标签搜索
        $model = new StoreItemTagModel();
        if($type){
            $model=$model->where('store_type',$type);
        }
        if($btype>0){
            $model=$model->where('booth_type',$btype);
        }
        if($price1>$price0){
            $model=$model->where('it.item_price','between',[$price0,$price1]);
        }
        if(!empty($key)){
            $model=$model->where('tag_value',$key);
        }
        $data = $model->alias('tag')
                ->join('store_tag_map tm','tm.tag_id=tag.id')
                ->join('store_item it','it.id=tm.item_id')
                ->field('it.*')->paginate(20);
        $data2 = $data;
        $merge = [];
        foreach ($data1 as $value) {
            $value['item_icon'] = cmf_get_image_url($value['item_icon']);
            $value['detail_url'] = url('portal/mall/index',['id'=>$value['id']],true,true);
            $merge[$value['id']] = $value;
        }
        foreach ($data2 as $value) {
            $value['item_icon'] = cmf_get_image_url($value['item_icon']);
            $value['detail_url'] = url('portal/mall/index',['id'=>$value['id']],true,true);
            $merge[$value['id']] = $value;
        }
//        $list = [];
//        foreach ($merge as $item){
//            $list[] = $item;
//        }
        
        $items = $data->toArray();
        $items['data']=array_values($merge);
        $items['price_range']=$priceRange;
        $this->success('ok'.$key,$items);
    }
    
    
    /**
     * 展位内藏品列表,传入type:展位ID
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/digital_list",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="type", type="integer", example="10,输入展位的ID"),
     *             @OA\Property(property="price_min", type="number", example="价格区间,默认为0"),
     *             @OA\Property(property="price_max", type="number", example="价格区间,如果区间max值大于min,则生效,否则忽略")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function digital_list(){
        $model = new StoreModel();
        $type = $this->request->post('type');
        
        $price0 = $this->request->post('price_min',0);
        $price1 = $this->request->post('price_max',0);

//        $key = $this->request->post('key');
//        $type = $this->request->post('type');
//       
//        //根据名称,类型搜索
//        $model = new StoreModel();
//        if($type){
//            $model=$model->where('store_type',$type);
//        }
//        $min = $model->field('item_price')->order('item_price asc')->find();
//        $max = $model->field('item_price')->order('item_price desc')->find();
//        $priceRange = ['min'=>$min['item_price'],'max'=>$max['item_price']];
        
        if($price1>$price0){
            $model=$model->where('item_price','between',[$price0,$price1]);
        }
        
        $data = $model->where('store_type',$type)->order('item_order asc')->paginate(20);

        foreach ($data as $key => $value) {
            $data[$key]['item_icon'] = cmf_get_image_url($value['item_icon']);
            $data[$key]['video_url'] = empty($value['video_url'])?"":cmf_get_image_url($value['video_url']);
            $data[$key]['detail_url'] = url('portal/mall/index',['id'=>$value['id']],true,true);
        }

        $items = $data->toArray();
        $this->success('ok'.$type,$items);
    }
    
    
    /**
     * 分类列表
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/type_list",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function type_list():void{
        $model = new StoreModel();
        $types = $model->types();
        $this->success('ok',$types);
    }
   
    /**
     * 标签列表,获取商品标签,根据标签来检索商品
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/tag_list",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="tag_type", type="integer", example="1数藏商城 2美容院 3零售区")
     *            

     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function tag_list(){
        $model = new StoreItemTagModel();
        Log::error('log_tag_list');
        Log::error('post:'.print_r($this->request->post(),true));
        Log::error('get:'.print_r($this->request->get(),true));
        $type = $this->request->post('tag_type/d',0);
        $store_type = $this->request->post('store_type/d',0);
        $list = $model->where('tag_type',$type)->whereOr('tag_type',0)->select();
        $itemModel = new StoreModel();
        $min = $itemModel->alias('item')->join('store_attr_map map','map.item_id=item.id')->where('store_type',$store_type)->where('map.price','>',0)->field('map.price')->order('map.price asc')->find();
        $max = $itemModel->alias('item')->join('store_attr_map map','map.item_id=item.id')->where('store_type',$store_type)->field('map.price')->order('map.price desc')->find();
        $rs = ['price_min'=>0,'price_max'=>0,'list'=>$list];
        if($min){
            $rs['price_min'] = $min['price'];
            $rs['price_max'] = $max['price'];
        }
        $this->success('ok',$rs);
    }
    
    /**
     * 订单信息
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/buylog",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="type", type="integer", example="1数藏商城 2美容院 3零售区"),
     *             @OA\Property(property="id", type="string", example="输入商品ID,返回结果一定会有此商品的订单")

     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function buylog(){
        $type = $this->request->get('type',0);
        $db = Db::name('store_log')->where('user_id', $this->userId);
        if($type>0){
            $db = $db->where('booth_type',$type);
        }
        $rs = $db->order('id desc')->paginate(20);
        $items = $rs->toArray();
        $arr = [];
        foreach ($items['data'] as $v){
            $v['item_url'] = cmf_get_image_url($v['item_url']);
            $arr[] = $v;
        }
        $id = $this->request->get('id',0);
        if($id){
            
            $direct = Db::name('store_log')->where('item_id',$id)->where('user_id',$this->userId)->select();
            if($direct){
                $list = $direct->toArray();

                foreach ($list as $v){
                    $find = false;
                    foreach ($arr as $it){
                        if($it['id']==$v['id']){
                            $find = true;
                            break;
                        }
                    }
                    if(!$find){
                        $v['item_url'] = cmf_get_image_url($v['item_url']);
                        $arr[] = $v;
                    }
                }
            }
        }
        
        $items['data'] = $arr; 
        $this->success('ok',$items);
    }
    
    
    /**
     * 我的所有数字藏品信息
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/myntf",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function myntf(){
        $items = Db::name('digital_collect')->alias('log')->field('it.*,log.booth_idx,log.create_time pay_time')
                ->join('store_item it','log.item_id=it.id')
                ->where('log.user_id', $this->userId)->order('create_time desc')
                ->select();
        $arr = [];
        foreach ($items as $v){
            $v['item_icon'] = cmf_get_image_url($v['item_icon']);
            $v['video_url'] = cmf_get_image_url($v['video_url']);
            $v['model_url'] = cmf_get_image_url($v['model_url']);
            $arr[] = $v;
        }
        $this->success('ok',$arr);
    }
    
    
    /**
     * 删除订单
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/delbuglog",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example="订单ID:a122211bdd2")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function delbuglog(){
        $id = $this->request->post('id','');
        Db::name('store_log')->where('user_id', $this->userId)->where('id' ,$id)->delete();
        $this->success('ok',$id);
    }
    
    
    /**
     * 商品详情
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/item_detal",     
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example="ffagdgdfgaaa")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */    
    public function item_detail(){
        $id = $this->request->get('id');
        $store = new StoreModel();
        $item = $store->where('id',$id)->find();
        if(empty($item)){
            return $this->error('商品去哪了');
        }
        $attrModel = new StoreAttrModel();
        $attrs = $attrModel->where('item_id',$id)->order('main desc')->order('id asc')->field('id,main,attr_name')->select();
        $store->where('id',$id)->setInc('view_count');
        $attrValue = new StoreAttrValueModel();
        $values = $attrValue->where('v.item_id',$id)->alias('v')->field('id,attr_id,attr_value')
                ->order('order_id','asc')->order('v.id','asc')->select();
        $mapModel = new StoreAttrMapModel();
        $price = $mapModel->where('item_id',$id)->field('id,attr_value_id attrs,price,count')->select();
        $tmp = [];
        foreach ($attrs as $attr){
            $a = $attr;
            $vlist = [];
            foreach ($values as $value){
                if($value['attr_id']==$attr['id']){
                    $vlist[]=['id'=>$value['id'],'attr_value'=>$value['attr_value']];
                }
            }
            $a['values'] = $vlist;
            $tmp[] = $a;
        }
        $attr2 = Db::name('store_spattr')->field('attr_name,attr_value,item_order')->where('item_id',$id)->order('item_order','asc')->select();
        
        $data = $item->toArray();
        $data['item_icon'] = cmf_get_image_url($data['item_icon']);
        $data['video_url'] = empty($data['video_url'])?"":cmf_get_image_url($data['video_url']);
        $data['model_url'] = empty($data['model_url'])?"":cmf_get_image_url($data['model_url']);
        $data['attrs'] = $tmp;
        $data['price_count'] = $price;
        $data['attrx'] = $attr2;
        $this->success('ok',$data);        
    }
    

    
     /**
     * 添加商品到购物车
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/addshoppingcard",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example=""),
     *             @OA\Property(property="num", type="integer", example=""),            
     *             @OA\Property(property="values", type="string", example="25,43,44")

     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function addshoppingcard(){
//        $user = $this->user;
        $id = $this->request->post('id');
        $storeModel = new StoreModel();
        $item = $storeModel->where('id',$id)->find();
        if(empty($item)){
            $this->error('商品不存在');
        }
//        $sub_id = $this->request->post('sub_id');
        $num = $this->request->post('num',1);
        if($item->check_count){
            $value_idstr = trim(trim($this->request->post('values','')),',');
            if(empty($value_idstr)){
                $this->error('选择商品类型1'.$this->request->post('values'),$this->request->post());
            }
            $value_ids = explode(',', $value_idstr);
            if(empty($value_ids)){
                $this->error('选择商品类型2');
            }



            sort($value_ids,SORT_NUMERIC);
            $value_idstr = join(',', $value_ids);
            $attrModel = new StoreAttrMapModel();
            $attr = $attrModel->where('item_id',$id)->where('attr_value_id',$value_idstr)->find();
            if(empty($attr)){
                $this->error('选择商品类型');
            }
            $attrValue = new StoreAttrValueModel();
            $values = $attrValue->whereIn('v.id',$value_ids)->alias('v')
                    ->order('order_id asc')->select();
            $price = $attr['price'];
            $count = $attr['count'];
            $sub_id = $attr['id'];
            $desc = '';
            if($num>$count){
                $this->error('库存不足');
            }
            foreach ($values as $v){
                $desc .= ','.$v['attr_value'];
            }
            
        }else{
            $price = $item['item_price'];
            $value_idstr = '';
            $sub_id = 0;
            $desc = '';
        }
        
        if($price==0){
            $this->error('选择商品类型');
        }
        
        $data = ['user_id'=>$this->userId,'sub_id'=>$sub_id,'num'=>$num,'item_id'=>$id,'price'=>$price,'values'=>$value_idstr,'desc'=>$item['item_name'].' '.$desc,'create_time'=> time()];
        $shopModel = new ShoppingcardModel();
        $shopModel->insert($data);
        $this->success('ok',$data);
    }
    
    /**
     * 购物车列表
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/shoppingcard",   
     *     @OA\Parameter(
     *          name="booth_type",
     *         @OA\Schema(
     *             type="int",
     *             format="type"
     *         ),
     *         in="query",
     *         description="展位类型,数字典藏:1 美容院:2,零售区:3 ,不限制区域:0",
     *         example="1",
     *         required=false
     *     ),  
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */  
    public function shoppingcard(){
        $shoppingcard = new ShoppingcardModel();
        $booth_type = $this->request->get('booth_type/d',0);
        if($booth_type==1){
            $list = $shoppingcard->alias('c')->where('it.booth_type',1)
                ->field('c.*,it.item_name,it.item_icon,item_desc,item_price,item_status,booth_type,item_num count')
                ->join('store_item it','c.item_id=it.id')->where('c.user_id',$this->userId)->order('c.id desc')->select();
            
        }elseif($booth_type>1){
            $list = $shoppingcard->alias('c')->where('it.booth_type',$booth_type)
                ->field('c.*,it.item_name,it.item_icon,item_desc,item_price,item_status,booth_type,map.count')
                ->join('store_item it','c.item_id=it.id')->join('store_attr_map map','map.id=c.sub_id')->where('c.user_id',$this->userId)->order('c.id desc')->select();
        }else{
            $list = $shoppingcard->alias('c')
                ->field('c.*,it.item_name,it.item_icon,item_desc,item_price,item_status,booth_type,map.count')
                ->join('store_item it','c.item_id=it.id')->join('store_attr_map map','map.id=c.sub_id')->where('c.user_id',$this->userId)->order('c.id desc')->select();
        }
        
        $arr = [];
        foreach ($list as $v){
            $v['item_icon'] = cmf_get_image_url($v['item_icon']);
            $arr[] = $v;
        }
        $this->success('ok'.$booth_type,$arr);
    }
    
         /**
     * 修改购物车属性
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/change_shoppingcard",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example="购物车ID"),
     *             @OA\Property(property="num", type="integer", example=""),            
     *             @OA\Property(property="values", type="string", example="25,43,44")

     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function change_shoppingcard(){
        $id = $this->request->post('id');
        $shopModel = new ShoppingcardModel();
        $shoppingcard = $shopModel->where('id',$id)->where('user_id',$this->userId)->find();
        if(empty($shoppingcard)){
            $this->error('购物车不存在');
        }
        $item_id = $shoppingcard['item_id'];
        $num = $this->request->post('num',1);
        $storeModel = new StoreModel();
        $item = $storeModel->where('id',$item_id)->find();
        if(empty($item)){
            $this->error('商品不存在');
        }
        if($item->check_count){
            $value_idstr = trim(trim($this->request->post('values','')),',');
            if(empty($value_idstr)){
                $this->error('选择商品类型1'.$this->request->post('values'),$this->request->post());
            }
            $value_ids = explode(',', $value_idstr);
            if(empty($value_ids)){
                $this->error('选择商品类型2');
            }

            $attrModel = new StoreAttrModel();
            $attrs = $attrModel->where('item_id',$item_id)->order('main asc')->select();

            $attrValue = new StoreAttrValueModel();
            $values = $attrValue->whereIn('v.id',$value_ids)->alias('v')->join('store_attr_map m','v.id=m.attr_value_id','left')
                    ->order('order_id asc')->select();
            $price = 0;
            $count = 0;
            $sub_id = 0;
            $desc = '';
            foreach ($attrs as $attr){
                $desc .= $attr['attr_name'].':';
                foreach ($values as $v){
                    if($v['attr_id']==$attr['id']){
                        $desc .= $v['attr_value'].',';
                        if($attr['main']){
                            $price = $v['price'];
                            $count = $v['count'];
                            $sub_id = $v['id'];
                        }
                    }
                }
            }
            if($price==0){
                $this->error('选择商品类型');
            }
            if($num>$count){
                $this->error('库存不足');
            }
        }else{
            $sub_id = 0;
            $price = $item->item_price;
            $num = 1;
        }
        
        
        $data = ['user_id'=>$this->userId,'sub_id'=>$sub_id,'num'=>$num,'item_id'=>$item_id,'price'=>$price,'values'=>$value_idstr,'desc'=>$item['item_name'].' '.$desc,'create_time'=> time()];

        $shopModel->where('id',$id)->update($data);
        $this->success('ok',$data);
    }


    /**
     * 删除购物车物品
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/delshoppingcard",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example="购物车ID, 333")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function delshoppingcard(){
        $id = $this->request->post('id');
        $shoppingcard = new ShoppingcardModel();
        $shoppingcard->where('id',$id)->where('user_id',$this->userId)->delete();
        $this->success('ok',$id);
    }
    
    /**
     * 数字典藏展位列表
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/booth",     
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function booth(){
        return $this->_booth(1);
    }
    /**
     * 美容院展位列表
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/salon",     
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */  
    public function salon(){
        return $this->_booth(2);
    }
    
    /**
     * 零售区展位列表
     * @OA\Get(
     *     tags={"mall-store"},
     *     path="/mall/store/retail",     
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */  
    public function retail(){
        return $this->_booth(3);
    }
    public function _booth($type){
        $model = new \api\mall\model\StoreBoothModel();
        $list = $model->where('booth_type',$type)->select();
        $arr = [];
        foreach ($list as $item){
            $item['icon'] = cmf_get_image_url($item['icon']);
            $item['model_url'] = cmf_get_image_url($item['model_url']);
//            $item['item_icon'] = cmf_get_image_url($item['item_icon']);
            $arr[] = $item;
        }
        $this->success('ok',$arr);
    }
    
    /**
     * 确认收货,已发货的标记:status=2,已确认收货status=3
     * @OA\Post(
     *     tags={"mall-store"},
     *     path="/mall/store/confirm",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="string", example="订单ID:MTM2024081212080899870")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function confirm(){
        $id = $this->request->post('id');
        $model = new StoreLogModel();
        $order = $model->where('id',$id)->where('status',2)->field('group_id')->find();
        if($order){
            //同一个订单都收货?
//            $model->where('group_id',$order->group_id)->update([
            //单个订单收货
            $model->where('id',$id)->update([
            'status'=>3,'desc'=>'确认收货'
        ]);
        }
        $this->success('ok');
    }

    

}
